<script setup lang="ts">
import { reactive, provide } from "vue";
import { onLaunch, onShow, onHide } from "@dcloudio/uni-app";
import { updateMp } from "@/utils/validate";
import { LOGIN_STATUS, USER_INFO } from "@/config/cache.js";
import Cache from "@/utils/cache";
import { toLogin } from "@/libs/login.js";
import themeList from "@/utils/theme";
import { onMounted } from "vue";
import protectH5 from "@/utils/protectH5";
import WebsocketUtil from "@/utils/webSocket.ts";
import { isWeixin } from "./utils";
import { getBaseUrl } from "@/utils/env";
import { getUserInfo, getCurlOauth, getOpenidByCode } from "@/api/user";
import { getWechatShare } from "@/api/public";
import wx from "weixin-js-sdk";
const baseURL = getBaseUrl();
const websocketUtil = new WebsocketUtil(); // 创建 WebSocket 工具类实例
provide("websocketUtil", websocketUtil); // 提供给所有子组件

// 设置主题样式
function setThemeHandler(themeValue, subThemeValue) {

  // 合并默认主题
  const mergedTheme =
    themeList["theme"][themeValue] + themeList["sub_theme"][subThemeValue];

  uni.setStorageSync("viewColor", mergedTheme);
}
let userInfo = "";
if (Cache.get(USER_INFO)) {
  userInfo = JSON.parse(Cache.get(USER_INFO));
}

// 初始化websocket
function webSoketInitHandler() {
  webSoketInit();
}
function parseUrlParams() {
  const params: any = {};

  // #ifdef H5
  // 解析history模式下的URL参数
  if (window.location.search) {
    const urlParams = new URLSearchParams(window.location.search);
    for (const [key, value] of urlParams) {
      params[key] = value;
    }
  }

  // 解析hash模式下的参数（如果存在）
  if (window.location.hash.includes("?")) {
    const hashParams = window.location.hash.split("?")[1];
    if (hashParams) {
      const hashSearchParams = new URLSearchParams(hashParams);
      for (const [key, value] of hashSearchParams) {
        params[key] = value;
      }
    }
  }
  // #endif

  return params;
}
onLaunch(() => {
  const queryData = uni.getEnterOptionsSync(); // uni-app版本 3.5.1+ 支持
  // 合并各种方式获取的参数
  const urlParams = parseUrlParams();

  const finalQuery = {
    ...queryData.query,
    ...urlParams,
  };

  setDefaultThemeHander();
  wxConfigHandler();

  // #ifdef MP
  updateMp();
  // #endif
});
onShow(() => {
  console.log("App Show");
});
onHide(() => {
  console.log("App Hide");
});
onMounted(() => {
  // #ifdef H5
  // 禁止打开F12
  protectH5();
  // #endif
});
// 获取当前页面URL
function getCurrentUrl() {
  return window.location.href.split("#")[0]; // 移除hash部分
}
// 配置wxsdn
function wxConfigHandler() {
  if (isWeixin()) {
    // 设置config  jssdk
    uni.request({
      url: "https://bjapi.yjgold.cn/bjp/api.wechat/jssdk",
      method: "get",
      data: {
        url: getCurrentUrl(),
      },
      success: function (res) {
        const data = res.data.data;

        wx.config({
          debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
          appId: data.appId, // 必填，公众号的唯一标识
          timestamp: data.timestamp, // 必填，生成签名的时间戳
          nonceStr: data.nonceStr, // 必填，生成签名的随机串
          signature: data.signature, // 必填，签名
          jsApiList: data.jsApiList || [
            "checkJsApi",
            "requestSubscribeMessage",
            "subscribeConfig",
          ], // 必填，需要使用的JS接口列表
          openTagList: ["wx-open-subscribe"],
        });
      },
      fail: function (err) {
        console.log(err);
      },
    });
  }
}
// 设置默认主题
function setDefaultThemeHander() {
  if (userInfo) {
    // 优先以themeValue主题优先（解决PC端刷新初始颜色不对的bug）
    if (Cache.get("themeValue")) {
      setThemeHandler(Cache.get("themeValue"), "golden");
      return;
    }
    // 获取缓存中的主题
    setThemeHandler(
      userInfo.theme || "dark",
      userInfo.theme_colour || "golden"
    );
  } else {
    // 缓存中没有主题信息，theme则使用列表中的黑色作为默认主题
    const themeKeys = Object.keys(themeList["theme"]);
    const subThemeKeys = Object.keys(themeList["sub_theme"]);
    // 默认选择第一个主题和第一个子主题
    const defaultThemeKey = themeKeys.length > 0 ? themeKeys[1] : "dark";
    const defaultSubThemeKey =
      subThemeKeys.length > 0 ? subThemeKeys[0] : "golden";
    console.log(defaultThemeKey, "默认");

    setThemeHandler(defaultThemeKey, defaultSubThemeKey);
    uni.setStorageSync("themeValue", defaultThemeKey);
    uni.setStorageSync("subThemeValue", defaultSubThemeKey);
  }
}
</script>

<style lang="scss">
@import "uview-plus/index.scss";
@import "@/static/css/flex.scss";
@import "@/static/css/base.scss";
@import "static/iconfont/iconfont.css";
uni-modal {
  z-index: 999999 !important;
}
@font-face {
  font-family: "NotoSansSC";
  src: url("https://bjapi.yjgold.cn/fonts/NotoSansSC.ttf");
}

.swiper_box {
  height: 160rpx;
}
.blod_class {
  font-weight: bold;
}
.no_blod {
  font-weight: normal !important;
}
.empty_box {
  padding-top: 200rpx;
}
.dark_font {
  color: #000 !important;
}
.colorGreen {
  color: rgb(2, 250, 1) !important;
  filter: brightness(0.7);
  // color: #17a650 !important;
}
// 深色主题的绿色
.colorGreenLight {
  color: #0f0;
  filter: unset;
}
.dead {
  filter: brightness(0.7);
}
.colorRed {
  color: #ff0000 !important;
  // color: #d90506 !important;
}
.theme_btn {
  border-radius: 20rpx;

  box-shadow: 0px 4px 20px 0px rgba(221, 203, 157, 0.4);
  background: var(--view-theme);
  color: var(--view-fontColor);
  font-size: 30rpx;
  width: 600rpx;
  height: 88rpx;
  line-height: 88rpx;
  margin: 0 auto;
  text-align: center;
  font-weight: bold;
}

.logon {
  font-size: 34rpx;
  color: #fff;
  font-weight: 700;
  height: 86rpx;
  line-height: 86rpx;
  text-align: center;

  margin-top: 60rpx;
  border-radius: 20rpx;
  color: #2e2e2e;
  box-shadow: 0px 4px 20px 0px rgba(221, 203, 157, 0.4);
  background: var(--view-theme);
}
</style>
